<template>
  <div class="container">
    <!-- 操作按钮 -->
    <div class="actions">
      <button class="btn-add" @click="handleAdd">
        <span class="icon">+</span> 添加用户
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>手机号</th>
            <th>用户类型</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in userList" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ user.user_type === 'normal' ? '普通用户' : '管理员' }}</td>
            <td>
              <button class="btn-edit" @click="handleEdit(user.id)">编辑</button>
              <button class="btn-delete" @click="handleDelete(user.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑模态框 -->
    <dialog ref="dialogRef" class="modal-dialog">
      <div class="modal-content">
        <h3>{{ modalTitle }}</h3>
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label>用户名：</label>
            <input v-model="formData.username" type="text" required>
          </div>
          <div class="form-group">
            <label>密码：</label>
            <input v-model="formData.password" type="password" :placeholder="modalTitle === '编辑用户' ? '留空则不修改密码' : '请输入密码'">
          </div>
          <div class="form-group">
            <label>用户类型：</label>
            <select v-model="formData.user_type" class="form-select">
              <option value="normal">普通用户</option>
              <option value="admin">管理员</option>
            </select>
          </div>
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="closeModal">取消</button>
            <button type="submit" class="btn-confirm">确认</button>
          </div>
        </form>
      </div>
    </dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/http';

const userList = ref([]);
const dialogRef = ref(null);
const modalTitle = ref('编辑用户');
const formData = ref({
  username: '',
  password: '',
  user_type: 'normal',
  id: null
});

// 初始化加载数据
onMounted(() => {
  fetchUserList();
});

// 获取用户列表
const fetchUserList = () => {
  http({
    method: 'get',
    url: 'users/'
  }).then(resp => {
    userList.value = resp.data.data;
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    alert('获取用户列表失败，请稍后重试');
  });
};

// 打开添加模态框
const handleAdd = () => {
  modalTitle.value = '添加用户';
  formData.value = {
    username: '',
    password: '',
    user_type: 'normal',
    id: null
  };
  dialogRef.value.showModal();
};

// 打开编辑模态框
const handleEdit = (userId) => {
  const user = userList.value.find(u => u.id === userId);
  if (user) {
    modalTitle.value = '编辑用户';
    formData.value = {
      username: user.username,
      password: '', // 编辑时不显示原密码
      user_type: user.user_type,
      id: user.id
    };
    dialogRef.value.showModal();
  }
};

// 删除用户
const handleDelete = (userId) => {
  if (confirm('确定要删除该用户吗？')) {
    http({
      method: 'DELETE',
      url: `users/${userId}/`
    }).then(() => {
      alert('删除成功');
      fetchUserList();
    }).catch(error => {
      console.error('删除失败:', error);
      alert(error?.response?.data?.message || '删除失败，请稍后重试');
    });
  }
};

// 提交表单
const submitForm = () => {
  // 验证必填字段
  if (!formData.value.username) {
    alert('请填写用户名');
    return;
  }

  // 添加用户时需要密码
  if (modalTitle.value === '添加用户' && !formData.value.password) {
    alert('添加用户时必须设置密码');
    return;
  }

  let apiUrl, method;
  if (modalTitle.value === '添加用户') {
    apiUrl = 'users/';
    method = 'POST';
  } else {
    apiUrl = `users/${formData.value.id}/`;
    method = 'PUT';
  }

  // 构建请求数据
  const requestData = {
    username: formData.value.username,
    user_type: formData.value.user_type
  };

  // 只有密码不为空时才包含密码字段
  if (formData.value.password) {
    requestData.password = formData.value.password;
  }

  http({
    method,
    url: apiUrl,
    data: requestData
  }).then(() => {
    alert(modalTitle.value === '添加用户' ? '添加成功' : '编辑成功');
    closeModal();
    fetchUserList();
  }).catch(error => {
    console.error('提交失败:', error);
    alert(error?.response?.data?.message || '提交失败，请稍后重试');
  });
};

// 关闭模态框
const closeModal = () => {
  dialogRef.value.close();
};
</script>

<style scoped>
/* 使用与第一个示例完全相同的样式 */
.container {
  padding: 20px;
  font-family: Arial, sans-serif;
  color: #333;
}

.actions {
  margin-bottom: 20px;
}

.btn-add {
  background-color: #4CAF50;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.btn-add:hover {
  background-color: #45a049;
}

.icon {
  margin-right: 5px;
  font-weight: bold;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  font-size: 14px;
}

.data-table th, 
.data-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  vertical-align: middle;
}

.data-table th {
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.data-table tr:hover {
  background-color: #f1f1f1;
}

.btn-edit, .btn-delete {
  padding: 6px 12px;
  margin: 0 2px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 13px;
}

.btn-edit {
  background-color: #2196F3;
  color: white;
}

.btn-delete {
  background-color: #f44336;
  color: white;
}

.btn-edit:hover {
  background-color: #0b7dda;
}

.btn-delete:hover {
  background-color: #da190b;
}

.modal-dialog {
  align-self: center;
  justify-self:center;
  width: 80%;
  max-width: 600px;
  border: none;
  border-radius: 6px;
  padding: 0;
  box-shadow: 0 3px 9px rgba(0,0,0,0.3);
}

.modal-dialog::backdrop {
  background: rgba(0, 0, 0, 0.5);
}

.modal-content {
  padding: 20px;
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-select {
  height: 36px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.btn-confirm, .btn-cancel {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-confirm {
  background-color: #4CAF50;
  color: white;
}

.btn-cancel {
  background-color: #f44336;
  color: white;
}

.btn-confirm:hover {
  background-color: #45a049;
}

.btn-cancel:hover {
  background-color: #da190b;
}

@media (max-width: 768px) {
  .data-table {
    font-size: 13px;
  }
  
  .data-table th, 
  .data-table td {
    padding: 8px;
  }
  
  .btn-edit, .btn-delete {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>